<template>
  <div class="topbar">
    <div class="topbar-wrapper center-wrapper">
      <div class="topbar-left">
        <img
          class="topbar-left-logo"
          src="@/assets/img/logo/logo.png"
          @click.stop="handleLOGOClick"
        />

        <div class="topbar-left-tabs">
          <el-tabs v-model="currentTab" class="demo-tabs" @tab-click="handleTabClick">
            <template v-for="tabItem in tabs" :key="tabItem.name">
              <el-tab-pane :label="tabItem.label" :name="tabItem.name"></el-tab-pane>
            </template>
          </el-tabs>
        </div>
      </div>

      <div class="topbar-right">
        <dropdown ref="dropdownRef" open-way="none">
          <div class="topbar-right-search">
            <input
              class="ipt"
              type="text"
              placeholder="搜索文章，用户..."
              v-model.trim="searchVal"
              @focus="handleSearchFocus"
              @input="handleSearchInpuing"
              @keyup.enter="handleSearchItemClick(searchRes.article[0] ?? searchRes.user[0])"
            />
            <img
              class="icon_search"
              src="@/assets/img/icons/icon_search.png"
              alt="搜索"
              @click.stop="handleSearchItemClick(searchRes.article[0] ?? searchRes.user[0])"
            />
          </div>

          <template #list>
            <div class="search-dropdown">
              <topbar-search-card
                v-show="searchRes.article.length > 0"
                title="文章"
                titleBgc="#DAE9FF"
                :details="searchRes.article"
                isMore
                :search-val="searchVal"
                @click-search-item="handleSearchItemClick"
                @click-search-more="handleSearchMore"
              ></topbar-search-card>
              <topbar-search-card
                v-show="searchRes.user.length > 0"
                title="用户"
                titleBgc="#FFF6E8"
                :details="searchRes.user"
                @click-search-item="handleSearchItemUserClick"
              ></topbar-search-card>

              <div
                v-show="searchRes.article.length <= 0 && searchRes.user.length <= 0"
                class="none-tip none-tip-pro"
              >
                未搜索到结果~
              </div>
            </div>
          </template>
        </dropdown>

        <div class="topbar-right-action publish">
          <el-dropdown popper-class="el-publish-dropdown">
            <button class="topbar-right-action-btn publish-btn">
              <img class="icon-frame" src="@/assets/img/icons/icon_frame.png" alt="发布" />
              发布
              <img
                class="icon-arrow-down"
                src="@/assets/img/icons/icon_arrow_down.png"
                alt="发布"
              />
            </button>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  class="el-publish-dropdown-item"
                  @click="handlePublish('article')"
                >
                  <Reading class="reading" />
                  发布文章
                </el-dropdown-item>

                <el-dropdown-item
                  class="el-publish-dropdown-item"
                  divided
                  @click="handlePublish('model')"
                >
                  <Box class="reading" />
                  发布模型
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <template v-if="loginStore.token">
            <el-dropdown popper-class="el-avatar-dropdown">
              <img class="avatar" :src="userInfo.avatar" alt="" v-if="userInfo.avatar" />
              <img class="avatar" src="@/assets/img/default/default_avatar.png" v-else />

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleMenuItemClick('profile')"
                    >个人主页</el-dropdown-item
                  >
                  <el-dropdown-item divided @click="handleMenuItemClick('logout')"
                    >退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <button class="topbar-right-action-btn login-btn" @click="useRouterJump('/login')">
              登录
            </button>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import TopbarSearchCard from './cpns/TopbarSearchCard.vue'
import useRouterJump from '@/hooks/useRouterJump'
import useLoginStore from '@/stores/login/login'
import useTopbarStore from '@/stores/topbar/topbar'
import useProfileStore from '@/stores/profile/profile'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { watch, ref } from 'vue'
import { useRoute } from 'vue-router'
import { throttle } from 'lodash'

// ====== store/route
const route = useRoute()
const topbarStore = useTopbarStore()
const loginStore = useLoginStore()
const profileStore = useProfileStore()
const { tabs, currentTab, searchRes } = storeToRefs(topbarStore)
const { isEditArticle, userInfo, isProfileChange } = storeToRefs(profileStore)

// ====== data
const dropdownRef = ref<any>()
const searchVal = ref<string>('')

// ====== watch
watch(
  () => route.path,
  newVal => {
    for (let item of tabs.value) {
      if (String(newVal).includes(item.name)) {
        currentTab.value = item.name
      }
    }
  }
)

// ====== methods
const handleMenuItemClick = (type: 'profile' | 'logout') => {
  switch (type) {
    case 'profile':
      isEditArticle.value = false
      useRouterJump('/profile', {})
      setTimeout(() => {
        if (route.path.includes('profile')) {
          isProfileChange.value = !isProfileChange.value
        }
      }, 100)

      break
    case 'logout':
      isEditArticle.value = false
      loginStore.logoutAction()
      break
  }
}
const handleTabClick = (pane: any) => {
  useRouterJump(`/${pane.paneName}`)
}
const handlePublish = (type: 'article' | 'model') => {
  if (!loginStore.token) {
    ElMessage({ message: '请先登录!', type: 'warning' })
    useRouterJump('/login')
  } else {
    // if (route.path == '/profile' && isEditArticle.value) return
    switch (type) {
      case 'article':
        isEditArticle.value = true
        if (route.path.includes('profile')) {
          useRouterJump('/profile', {})
        } else {
          useRouterJump('/profile')
        }

        break
      case 'model':
        ElMessage({ message: '敬请期待', type: 'success' })
        break
    }
  }
}
const handleSearchFocus = () => {
  if (searchVal.value.length > 0) {
    dropdownRef.value?.openDropdown()
  }
}
const handleSearchInpuing = throttle(() => {
  topbarStore.selectList({
    pageNum: 1,
    pageSize: 5,
    title: searchVal.value
  })

  if (searchVal.value.length > 0 && !dropdownRef.value?.isShowCpt) {
    dropdownRef.value?.openDropdown()
  }
}, 800)
const handleSearchItemClick = (payload: any) => {
  if (payload && payload.nickname) {
    searchVal.value = ''
    useRouterJump('/profile', { userId: payload.user_id })
    setTimeout(() => {
      if (route.path.includes('profile')) {
        isProfileChange.value = !isProfileChange.value
      }
    }, 100)
  } else if (payload && payload.id) {
    searchVal.value = ''
    useRouterJump('/article-detail', { articleId: payload.id })
  }

  dropdownRef.value?.closeDropdown()
}
const handleSearchItemUserClick = (payload: any) => {
  if (payload && payload.nickname) {
    searchVal.value = ''
    useRouterJump('/profile', { userId: payload.user_id })
    setTimeout(() => {
      if (route.path.includes('profile')) {
        isProfileChange.value = !isProfileChange.value
      }
    }, 100)
  }

  dropdownRef.value?.closeDropdown()
}
const handleSearchMore = () => {
  searchRes.value.searchMore = searchVal.value
  useRouterJump('/article')

  dropdownRef.value?.closeDropdown()
}
const handleLOGOClick = () => {
  useRouterJump('/', {})
}
</script>

<style lang="less" scoped>
.topbar {
  width: 100%;
  height: 112px;
  background: #ffffff;
  box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.1);

  .topbar-wrapper {
    display: flex;

    .topbar-left,
    .topbar-right {
      flex: 1;
      display: flex;
      align-items: center;
    }

    .topbar-left {
      justify-content: flex-start;

      .topbar-left-logo {
        width: 157px;
        cursor: pointer;
      }

      :deep(.topbar-left-tabs) {
        margin-left: 77px;

        .el-tabs__header {
          margin: 0;

          .el-tabs__nav-wrap::after {
            display: none;
          }

          .el-tabs__item {
            font-size: 21px;
            font-weight: 500;
            color: #333333;
            // padding: 0 32px 0 0;

            &.is-active {
              color: #0075ff;
            }
          }

          .el-tabs__active-bar {
            background-color: #0075ff;
          }
        }
        .el-tabs__content {
          display: none;
        }
      }
    }

    .topbar-right {
      justify-content: flex-end;

      .topbar-right-search {
        display: flex;
        align-items: center;
        width: 451px;
        height: 56px;
        background: #f2f2f2;
        border-radius: 8px;
        font-size: 19px;
        font-weight: normal;
        box-sizing: border-box;
        padding: 0 11px 0 27px;

        input::input-placeholder {
          color: #979797;
        }
        input::-webkit-input-placeholder {
          color: #979797;
        }
        input::-moz-placeholder {
          color: #979797;
        }
        input:-moz-placeholder {
          color: #979797;
        }
        input::-ms-input-placeholder {
          color: #979797;
        }

        .ipt {
          background: none;
          outline: none;
          border: none;
          width: 100%;
          height: 100%;
        }

        .icon_search {
          width: 43px;
          cursor: pointer;
        }
      }

      .topbar-right-action {
        display: flex;
        align-items: center;
        margin-left: 45px;

        .topbar-right-action-btn {
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #0075ff;
          margin: 0;
          border: none;
          background: none;
          transition: all 0.3s ease;

          .icon-frame {
            width: 20px;
            margin-right: 7px;
          }
          .icon-arrow-down {
            width: 14px;
            margin-left: 1px;
          }
        }
        .publish-btn {
          width: 141px;
          height: 48px;
          border-radius: 0;
          border: 1px solid #0075ff;
          font-size: 20px;
          font-weight: 500;
        }
        .login-btn {
          width: 133px;
          height: 49px;
          background: #f8f8f8;
          border-radius: 64px;
          font-size: 21px;
          font-weight: bold;
          margin-left: 21px;
        }
        .topbar-right-action-btn:hover {
          opacity: 0.7;
          background-color: #0077ff20;
        }
      }

      .avatar {
        width: 53px;
        height: 53px;
        border-radius: 50%;
        margin-left: 40px;
        cursor: pointer;
      }
    }
  }

  .search-dropdown {
    .none-tip-pro {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100px;
    }
  }
}

:global(.el-dropdown-menu__item) {
  justify-content: center !important;
  font-size: 18px;
  height: 50px;
}
:global(.el-publish-dropdown) {
  .el-dropdown-menu__item {
    width: 141px;
  }
}
.reading {
  width: 20px;
  margin-right: 10px;
}
</style>
